package hotel.switchs.oversea.biz.service.impl;


import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.dto.switchs.SwitchMasterHotelInfoDto;
import hotel.base.oversea.service.impl.BaseServiceImpl;
import hotel.base.oversea.utils.JacksonUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.StringUtil;
import hotel.base.oversea.vo.ResultStatusInfoVo;
import hotel.switchs.oversea.api.VO.DltCoordinateEntityVo;
import hotel.switchs.oversea.api.VO.MasterInfoVo;
import hotel.switchs.oversea.api.VO.PagerVo;
import hotel.switchs.oversea.api.VO.SwitchMasterHotelVo;
import hotel.switchs.oversea.api.entity.SwitchMasterHotelInfo;
import hotel.switchs.oversea.biz.mapper.SwitchMasterHotelInfoMapper;
import hotel.switchs.oversea.biz.service.SwitchMasterHotelInfoService;
import hotel.switchs.oversea.biz.utils.BaseRqeuestParam;
import hotel.switchs.oversea.biz.utils.SwitchsHttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author lmf
 * @Date 2020/5/14 14:45
 **/
@Service
public class SwitchMasterHotelInfoServiceImpl  extends BaseServiceImpl<SwitchMasterHotelInfo> implements SwitchMasterHotelInfoService {
    Logger logger= LoggerFactory.getLogger(SwitchMasterHotelInfoServiceImpl.class);
    @Value("${profile.type}")
    private String profile;

    @Autowired
    private SwitchMasterHotelInfoMapper switchMasterHotelInfoMapper;
    /**
     * @param pageSize
     * @param pageIndex
     * @return
     * 获取母酒店列表
     */
    @Retryable(value = Exception.class,maxAttempts = 4,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public Result<Object> getMasterHotelList(Map<String,Object> param, int pageSize, int pageIndex) {
        BaseRqeuestParam baseRqeuestParam=new BaseRqeuestParam();
        Map<String, Object> data = new HashMap<>();
        Map<String,Object> pagingSettings=new HashMap<>();
        pagingSettings.put("pageSize",pageSize);
        pagingSettings.put("pageIndex",pageIndex);
        pagingSettings.put("isReturnTotalCount",true);
        data.putAll(param);
        data.put("requestor", baseRqeuestParam);
        data.put("pager",pagingSettings);
        String result= SwitchsHttpUtils.sendRequest(data,"getdltmasterhotellist",profile);
        //对结构进行格式化
        Map<String,Object> map = JacksonUtil.parse(result,Map.class);

        ResultStatusInfoVo resultStatusInfoVo= JacksonUtil.parse(JacksonUtil.objectToJson(map.get("resultStatus")),ResultStatusInfoVo.class);
        //说明调用接口失败
        if(resultStatusInfoVo.getResultCode()!=0){
            logger.info("获取母酒店列表错误信息{}",resultStatusInfoVo.getResultMsg());
            return new Result<>(resultStatusInfoVo.getResultMsg(),CommonConstants.REQUEST_ERROR);
        }
        System.out.println(resultStatusInfoVo.toString());
        //获取母酒店数据列表
        List<SwitchMasterHotelVo> switchHotelInfoVos=JacksonUtil.jsonToList(JacksonUtil.objectToJson(map.get("dltMasterHotelEntityList")), SwitchMasterHotelVo.class);
        //说明没有返回任何数据
        if(switchHotelInfoVos.size()<1){
            return new Result<>();
        }
        PagerVo pagerVo= JacksonUtil.parse(JacksonUtil.objectToJson(map.get("pager")), PagerVo.class);
        MasterInfoVo masterInfoVo=new MasterInfoVo();
        masterInfoVo.setDltMasterHotelEntityList(switchHotelInfoVos);
        masterInfoVo.setPager(pagerVo);
        return new Result<>(masterInfoVo);

    }

    /**
     * 保存母酒店数据
     * @param switchHotelInfoVosMap
     * @return
     */
    @Override
    public Result<Object> saveMasterHotelInfo(Map<String,List<SwitchMasterHotelVo>> switchHotelInfoVosMap){

        Map<String, String> putRedisMasterIdsMap = new HashMap<>();
        //将母酒店数据保存到redis：key=hotelId母酒店id，value=dto母酒店信息对象
        Map<String, SwitchMasterHotelInfoDto> putRedisHotelInfoMap = new HashMap<>();

        for(Map.Entry<String,List<SwitchMasterHotelVo>> entry:switchHotelInfoVosMap.entrySet()){
            List<SwitchMasterHotelInfo> switchMasterHotelInfos=new ArrayList<>();
            List<SwitchMasterHotelVo> switchHotelInfoVos = entry.getValue();
            StringBuilder sb = new StringBuilder();
            //封装成母酒店数据表单
            for (int i = 0; i < switchHotelInfoVos.size(); i++) {
                SwitchMasterHotelVo switchMasterHotelVo = switchHotelInfoVos.get(i);
                SwitchMasterHotelInfo switchMasterHotelInfo=new SwitchMasterHotelInfo();
                switchMasterHotelInfo.setMasterHotelId(switchMasterHotelVo.getMasterHotelID());
                /*if(!ObjectUtils.isEmpty(switchMasterHotelInfoMapper.selectOne(switchMasterHotelInfo))){
                    continue;
                }*/
                switchMasterHotelInfo.setId(StringUtil.getUUID());
                switchMasterHotelInfo.setCityId(switchMasterHotelVo.getCityID());
                switchMasterHotelInfo.setCityName(switchMasterHotelVo.getCityName());
                switchMasterHotelInfo.setHotelName(switchMasterHotelVo.getHotelName());
                switchMasterHotelInfo.setHotelEName(switchMasterHotelVo.getHotelEName());
                switchMasterHotelInfo.setHotelStar(switchMasterHotelVo.getHotelStar());
                switchMasterHotelInfo.setHotelAddress(switchMasterHotelVo.getHotelAddress());
                switchMasterHotelInfo.setHotelAddressEn(switchMasterHotelVo.getHotelAddressEn());
                switchMasterHotelInfo.setHotelPhone(switchMasterHotelVo.getHotelPhone());
                switchMasterHotelInfo.setCanAddHotel(switchMasterHotelVo.getCanAddHotel().equals("T")?1:0);
                switchMasterHotelInfo.setStarLicence(((switchMasterHotelVo.getStarLicence().equals("T"))?1:0));
                DltCoordinateEntityVo dltCoordinateEntityVo=switchMasterHotelVo.getDltCoordinateEntity();
                //说明有返回定位数据数据
                if(!ObjectUtils.isEmpty(dltCoordinateEntityVo)){
                    switchMasterHotelInfo.setGdLat(BigDecimal.valueOf(dltCoordinateEntityVo.getGlat()));
                    switchMasterHotelInfo.setGdLat(BigDecimal.valueOf(dltCoordinateEntityVo.getGDlat()));
                    switchMasterHotelInfo.setBdLat(BigDecimal.valueOf(dltCoordinateEntityVo.getBDlat()));
                    switchMasterHotelInfo.setBdLng(BigDecimal.valueOf(dltCoordinateEntityVo.getBDlng()));
                    switchMasterHotelInfo.setGgLat(BigDecimal.valueOf(dltCoordinateEntityVo.getGlat()));
                    switchMasterHotelInfo.setGgLng(BigDecimal.valueOf(dltCoordinateEntityVo.getGlng()));
                }
                switchMasterHotelInfo.setState(0);
                switchMasterHotelInfo.setCreateTime(new Date());
                switchMasterHotelInfo.setModifyTime(new Date());


                SwitchMasterHotelInfoDto switchMasterHotelInfoDto = new SwitchMasterHotelInfoDto();
                switchMasterHotelInfoDto.setMasterHotelId(switchMasterHotelInfo.getMasterHotelId());
                switchMasterHotelInfoDto.setCityName(switchMasterHotelInfo.getCityName());
                switchMasterHotelInfoDto.setHotelName(switchMasterHotelInfo.getHotelName());
                switchMasterHotelInfoDto.setGgLat(switchMasterHotelInfo.getGgLat());
                switchMasterHotelInfoDto.setGgLng(switchMasterHotelInfo.getGgLng());
                switchMasterHotelInfoDto.setGdLat(switchMasterHotelInfo.getGgLat());
                switchMasterHotelInfoDto.setGdLng(switchMasterHotelInfo.getGdLng());
                switchMasterHotelInfoDto.setBdLat(switchMasterHotelInfo.getBdLat());
                switchMasterHotelInfoDto.setBdLng(switchMasterHotelInfo.getBdLng());
                switchMasterHotelInfoDto.setHotelStar(switchMasterHotelInfo.getHotelStar());
                switchMasterHotelInfoDto.setCityId(switchMasterHotelInfo.getCityId());
                switchMasterHotelInfoDto.setHotelEName(switchMasterHotelInfo.getHotelEName());
                switchMasterHotelInfoDto.setStarLicence(switchMasterHotelInfo.getStarLicence());
                switchMasterHotelInfoDto.setHotelAddress(switchMasterHotelInfo.getHotelAddress());
                switchMasterHotelInfoDto.setHotelAddressEn(switchMasterHotelInfo.getHotelAddressEn());
                switchMasterHotelInfoDto.setHotelPhone(switchMasterHotelInfo.getHotelPhone());
                switchMasterHotelInfoDto.setCanAddHotel(switchMasterHotelInfo.getCanAddHotel());

                if(!(StringUtils.isEmpty(switchMasterHotelInfoDto.getHotelAddress()) && StringUtils.isEmpty(switchMasterHotelInfoDto.getBdLat())
                        && StringUtils.isEmpty(switchMasterHotelInfoDto.getGdLat()) && StringUtils.isEmpty(switchMasterHotelInfoDto.getGgLat()))){
                    //酒店地址+经纬度 都为空 则认为是无用酒店，不保存缓存,反之保存
                    putRedisHotelInfoMap.put(String.valueOf(switchMasterHotelInfo.getMasterHotelId()),switchMasterHotelInfoDto);
                    putRedisMasterIdsMap.put(String.valueOf(switchMasterHotelInfo.getMasterHotelId()),String.valueOf(switchMasterHotelInfo.getMasterHotelId()));

                }
                //数据不管是否地址为空都要保存到数据库
                switchMasterHotelInfos.add(switchMasterHotelInfo);
                sb.append("'"+switchMasterHotelInfo.getMasterHotelId()+"'");//拼接单引号,到数据库后台用in查询.
                if(i!=switchHotelInfoVos.size()-1){
                    sb.append(",");
                }

            }
            //旧数据删除，插入新数据
            Map map = new HashMap();
            map.put("ids",sb.toString());
            if(-1!=switchMasterHotelInfoMapper.deleteBatch(map)){
                switchMasterHotelInfoMapper.insertList(switchMasterHotelInfos);
            }

        }
        //保存母酒店dto对象数据   Map<String,SwitchMasterHotelInfoDto>  --》 key = 母酒店id，value=母酒店dto
        /*Object objHotelInfoRedis = redisService.get(CommonConstants.SWITCH_HOTEL_INFO);
        Map<String,SwitchMasterHotelInfoDto> redisMap = (Map<String,SwitchMasterHotelInfoDto>)objHotelInfoRedis;
        if(null != redisMap && redisMap.size()>0){
            redisMap.putAll(putRedisHotelInfoMap);
        }else{
            redisMap=putRedisHotelInfoMap;
        }
        redisService.set(CommonConstants.SWITCH_HOTEL_INFO,redisMap);*/

        //保存母酒店id数据  Map<String,String>  --》 key = 母酒店id，value= 母酒店id
       /* Map<String,String> redisMasterIdMap = (Map<String,String>)redisService.get(CommonConstants.SWITCH_MASTER_HOTEL_IDS_INFO);
        if(null != redisMasterIdMap && redisMasterIdMap.size()>0){
            redisMasterIdMap.putAll(putRedisMasterIdsMap);
        }else{
            redisMasterIdMap=putRedisMasterIdsMap;
        }
        redisService.set(CommonConstants.SWITCH_MASTER_HOTEL_IDS_INFO,redisMasterIdMap);*/
        return new Result<>();
    }


    @Override
    public List<SwitchMasterHotelInfoDto> queryPageReturnDto() {
        List<SwitchMasterHotelInfoDto> list = switchMasterHotelInfoMapper.queryPageReturnDto();
        return list;
    }


}
